import { useEffect } from 'react';
import { Button, Checkbox, Form, Input } from 'antd';
import { useModel } from '@umijs/max'
import { editEmployee, getEmployeeInfo } from './services'
import { queryRoleList } from '@/pages/system/roleList/services'
import { useRequest } from 'ahooks';

const RoleEditPage: React.FC<RoutePageProps> = (props) => {
  const [editForm] = Form.useForm()
  const { runAsync, loading } = useRequest(editEmployee, {manual: true})
  const { data: employeeInfo, runAsync: getData } = useRequest(getEmployeeInfo, {manual: true})
  const { data: roleList } = useRequest(() => queryRoleList({pageNum: 1, pageSize: 1000}))
  const { closeCurrentTab } = useModel('global')

  const onFinish = (formValues: any) => {
    runAsync({
      ...formValues,
      id: employeeInfo?.data.id,
    })
    .then(() => {
      const event = new CustomEvent('refreshEmployeeList')
      window.dispatchEvent(event)
      closeCurrentTab('/system/managerList')
    })
  }

  useEffect(() => {
    const { id } = props.params
    if (id) {
      getData({userId: Number(id)})
      .then(res => {
        const { data } = res
        editForm.setFieldsValue({
          telephone: data.telephone,
          username: data.username,
          roles: data.roleVos?.map(it => it.id),
        })
      })
    } else {
      editForm.setFieldsValue({
        telephone: undefined,
        username: undefined,
        roles: undefined,
      })
    }
  }, [props.params.id])
  
  return (
    <div className='container'>
      <div className="card">
        <Form form={editForm} name='editForm' labelCol={{flex: '120px'}} onFinish={onFinish}>
          <Form.Item name='username' label='员工姓名' rules={[{required: true, message: '请输入员工姓名'}]}>
            <Input placeholder='请输入' style={{width: 320}} />
          </Form.Item>
          <Form.Item name='telephone' label='登录账号' rules={[{required: true, message: '请输入手机号'}]}>
            <Input placeholder='请输入手机号' style={{width: 320}} />
          </Form.Item>
          <Form.Item name='roles' label='员工角色'>
            <Checkbox.Group
              options={roleList?.data.map(item => ({label: item.roleName, value: item.id}))}
            />
          </Form.Item>
          <Form.Item label=' ' colon={false}>
            <Button type='primary' htmlType='submit' loading={loading}>提交</Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
};

export default RoleEditPage;
